package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 后台登录
     *
     * @param map
     * @return
     */
    public Map login(Map map) {
        //获取请求登录的数据
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //判断密码是否正确和验证码是否一致
        //验证码存入redis中
        String key = Constants.CAP_CODE + uuid;
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code) || !verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        //删除redis缓存中的验证码
        redisTemplate.delete(key);
        //根据用户名查询管理员对象 admin
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);
        //判断用户是否存在，密码是否一致
        //给密码加密
        password = SecureUtil.md5(password);
        if (admin == null || !password.equals(admin.getPassword())) {
            throw new BusinessException("账号密码错误");
        }
        //生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        tokenMap.put("username",admin.getUsername());
        String token = JwtUtils.getToken(tokenMap);
        //构造返回值
        Map resMap=new HashMap();
        resMap.put("token",token);
        return resMap;
    }

    /**
     * 获取用户资料
     * @return
     */
    public AdminVo profile() {
        //获取当前用户id
        Long userId = AdminHolder.getUserId();
        //通过id获取用户
        Admin admin = adminMapper.selectById(userId);
        return AdminVo.init(admin);
    }

    /**
     * 退出，删除token
     */
    public void logout() {
        AdminHolder.remove();
    }
}
